#include "patientselectdialog.h"
#include "ui_patientselectdialog.h"

#include "sqlpatientmodel.h"
#include "../share/global.h"

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlRecord>

PatientSelectDialog::PatientSelectDialog(const QString &name, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PatientSelectDialog)
{
    ui->setupUi(this);

    pModel = new SqlPatientModel(this);
    QString query = QString("SELECT PatientId, PatientName, PatientSex, PatientBirth, PatientAge,"
            "MedicalAlerts, PatientSize, PatientWeight, PatientAddr, PatientPhone FROM "
            "StudyTable WHERE PatientName LIKE \'%%1%\'").arg(name);
    pModel->setQuery(query, QSqlDatabase::database(STUDY_DB_CONNECTION_NAME));
    ui->patientTableView->setModel(pModel);
    //ui->patientTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    if (pModel->rowCount()) ui->patientTableView->selectRow(0);
    connect(ui->selectButton, SIGNAL(clicked()), this, SLOT(onSelect()));
    connect(ui->patientTableView, SIGNAL(activated(QModelIndex)), this, SLOT(onItemActivated(QModelIndex)));
}

PatientSelectDialog::~PatientSelectDialog()
{
    delete ui;
}

void PatientSelectDialog::onSelect()
{
    onItemActivated(ui->patientTableView->currentIndex());
}

void PatientSelectDialog::onItemActivated(const QModelIndex &index)
{
    if (index.isValid()) {
        QSqlRecord rec = pModel->record(index.row());
        study.patientId = rec.value(SqlPatientModel::PatientId).toString();
        study.patientName = rec.value(SqlPatientModel::PatientName).toString();
        study.patientSex = rec.value(SqlPatientModel::PatientSex).toString();
        study.patientBirth = QDate::fromString(rec.value(SqlPatientModel::PatientBirth).toString(), "yyyy-MM-dd");
        study.patientAge = rec.value(SqlPatientModel::PatientAge).toString();
        study.medicalAlerts = rec.value(SqlPatientModel::MedicalAlerts).toString();
        study.patientSize = rec.value(SqlPatientModel::PatientSize).toString();
        study.patientWeight = rec.value(SqlPatientModel::PatientWeight).toString();
        study.patientAddr = rec.value(SqlPatientModel::PatientAddr).toString();
        study.patientPhone = rec.value(SqlPatientModel::PatientPhone).toString();
        accept();
    } else {
        QMessageBox::warning(this, tr("Patient Select"),
                             tr("Select one patient first."));
    }
}
